import 'dart:convert';
import 'package:crypto/crypto.dart';
import 'dart:typed_data';
import 'package:intl/intl.dart';
import 'log_utils.dart';

class StringUtils {
  static bool isEmpty(String? s) {
    return s == null || s.isEmpty;
  }

  ///使用sha1加密
  static String dartSha1(String data) {
    Uint8List content = const Utf8Encoder().convert(data);
    Digest digest = sha1.convert(content);
    return digest.toString();
  }

  ///使用md5加密
  static String dartMd5(String data) {
    Uint8List content = const Utf8Encoder().convert(data);
    Digest digest = md5.convert(content);
    return digest.toString();
  }

  static bool isNotEmpty(String? s) => !isEmpty(s);

  static bool isLink(String str) =>
      str.contains(RegExp(r'^(https?:\/\/)?([\w\d_-]+)\.([\w\d_\.-]+)\/?\??([^#\n\r]*)?#?([^\n\r]*)'));

  static String truncateWithEllipsis(int cutoff, String myString) {
    return (myString.length <= cutoff) ? myString : '${myString.substring(0, cutoff)}...';
  }

  static String printMap(Map<String, dynamic>? map) {
    String str = '';
    map?.forEach((key, value) => str += '$key: ${value.toString}, ');
    return str;
  }

  /// Gracefully handles null values, and skips the suffix when null
  static String safeGet(String value, [String? suffix]) {
    return value + (value.isNotEmpty ? suffix ?? '' : '');
  }

  static String capitalize(String value) {
    return '${value[0].toUpperCase()}${value.substring(1).toLowerCase()}';
  }

  static String supplant(String value, Map<String, String> supplants) {
    return value.replaceAllMapped(RegExp(r'\{\w+\}'), (match) {
      final placeholder = match.group(0) ?? '';
      if (supplants.containsKey(placeholder)) {
        return supplants[placeholder]!;
      }
      return placeholder;
    });
  }

  static String encryptPhoneNumber(String phoneNumber) {
    if (phoneNumber.length != 11) {
      // 假设手机号码长度为11位
      return phoneNumber;
    }

    String encryptedNumber = phoneNumber.substring(0, 3); // 取前三位
    encryptedNumber += '****'; // 添加四个星号
    encryptedNumber += phoneNumber.substring(7); // 取后四位

    return encryptedNumber;
  }

  /// 手机号脱敏
  static String? showNewNumber(String? account) {
    try {
      if (account != null && account.length == 11) {
        return "${account.substring(0, 3)}****${account.substring(7, 11)}";
      }
    } catch (e) {
      Log.d(e);
    }
    return account;
  }

  /// 银行卡脱敏
  static String formatBankNum(String bankAccount, int divisionCount) {
    var beginIndex = bankAccount.length - divisionCount;
    if (beginIndex < 0) return '';
    var startNum = bankAccount.substring(0, divisionCount);
    var middleNumLen = bankAccount.substring(divisionCount, beginIndex).length;
    var endNum = bankAccount.substring(beginIndex);
    var middleNumStr = StringBuffer();
    middleNumStr.write(" ");
    var starCount = "";
    for (int i = 0; i < divisionCount; i++) {
      starCount += "*";
    }
    for (int i = 0; i < middleNumLen; i++) {
      if ((i + 1) % divisionCount == 0) {
        middleNumStr.write(starCount);
        middleNumStr.write(" ");
      }
    }
    for (int i = 0; i < (middleNumLen % divisionCount); i++) {
      middleNumStr.write("*");
    }
    if (middleNumLen % divisionCount > 0) {
      middleNumStr.write(" ");
    }
    return startNum + middleNumStr.toString() + endNum;
  }

  /// 分 转换为 元 保留两位小数
  static String formatNumber(dynamic number) {
    try {
      var f = NumberFormat("0.00", "zh_CN");
      return number == null ? '0.00' : f.format(num.parse(number.toString()) / 100);
    } catch (e) {
      Log.e(e);
    }
    return '0.00';
  }

  /// *,***,*** 千分位展示
  static String thousandthFormat(num number) {
    NumberFormat formatter = NumberFormat.decimalPatternDigits(
      locale: 'zh_CN',
      decimalDigits: 0,
    );
    return formatter.format(number);
  }

  /// 16进制转10进制
  /// #000000 -》0
  static int getColor(String? color) {
    var colorStr = color?.replaceAll('#', 'FF') ?? '0';
    return int.tryParse(colorStr, radix: 16) ?? 0;
  }
}
